<template>
  <div>
    <template v-if="!$store.getters.screenWidth">
      <div class="order" v-for="(item,index) in orderList" :key="index">
        <div class="order_status">
          <div>
            <div class="order_status_title">{{getStatus(item.status,item.paid)}}</div>
            <div>订单号：{{item.orderId}}</div>
            <div
              style="text-align:left;margin-top:10px"
            >订单时间：{{item.addTime.slice(0,16).replace('T','-')}}</div>
            <div style="display:flex;align-items:center;margin-top:5px">
              <p>订单金额:</p>
              <p style="color:#f96868;font-size: 1.286rem;">￥{{item.payPrice}}元</p>
            </div>
          </div>
          <div>
            <div>
              <el-button
                type="danger"
                :loading="isLoading && item.id == itemid"
                v-if="item.paid==0"
                @click="pay(item)"
              >立即付款</el-button>
              <el-button
                type="danger"
                :loading="isLoading && item.id == itemid"
                v-if="item.paid==1 && item.status == 0"
                @click="rebturnMoney(item)"
              >申诉</el-button>
            </div>
          </div>
        </div>
        <div class="order_items">
          <div style="padding:20px;display:flex;justify-content:space-between">
            <div>
              <div
                class="order_item_detail"
                @click="toItem(item1)"
                v-for="(item1,index) in item.cartInfos"
                :key="index"
              >
                <div>
                  <img :src="JSON.parse(item1.cartInfo).product.image" style="width:60px;height:60px" alt />
                </div>
                <div style="margin-left:5px">
                  <div style="color: #62a8ea;font-size:14px;margin-bottom:7px">{{JSON.parse(item1.cartInfo).product.storeName}}</div>
                  <div style="text-align:left;">￥{{JSON.parse(item1.cartInfo).product.price}}元</div>
                  <div style="text-align:left;font-size:12px;">{{JSON.parse(item1.cartInfo).product.spec ? JSON.parse(JSON.parse(item1.cartInfo).product.spec).attrs[0].values.join(',') : ''}}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
    <template v-else>
      <div class="order" v-for="(item,index) in orderList" :key="index">
        <div class="order_status">
          <div>
            <div class="order_status_title">{{getStatus(item.status,item.paid)}}</div>
            <div>订单号：{{item.orderId}}</div>
            <div
              style="text-align:left;margin-top:10px"
            >订单时间：{{item.addTime.slice(0,16).replace('T','-')}}</div>
            <div style="display:flex;align-items:center;margin-top:5px">
              <p>订单金额:</p>
              <p style="color:#f96868;font-size: 1.286rem;">￥{{item.payPrice}}元</p>
            </div>
          </div>
          <div>
            <div>
              <el-button type="danger" v-if="item.paid==0" @click="payPhone(item)">立即付款</el-button>
              <el-button
                type="danger"
                :loading="isLoading && item.id == itemid"
                v-if="item.paid==1 && item.status == 0"
                @click="rebturnMoney(item)"
              >申诉</el-button>
            </div>
          </div>
        </div>
        <div class="order_items" style="border:none">
          <div style="padding:20px;display:flex;justify-content:space-between;padding-top:0">
            <div>
              <div
                class="order_item_detail"
                @click="toItem(item1)"
                v-for="(item1,index) in item.cartInfos"
                :key="index"
              >
                <div>
                  <img :src="JSON.parse(item1.cartInfo).product.image" style="width:60px;height:60px" alt />
                </div>
                <div style="margin-left:5px">
                  <div style="color: #62a8ea;font-size:14px;margin-bottom:7px">{{JSON.parse(item1.cartInfo).product.storeName}}</div>
                  <div style="text-align:left;">￥{{JSON.parse(item1.cartInfo).product.price}}元</div>
                  <div style="text-align:left;font-size:12px;">{{JSON.parse(item1.cartInfo).product.spec ? JSON.parse(JSON.parse(item1.cartInfo).product.spec).attrs[0].values.join(',') : ''}}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>

    <div
      v-if="orderList.length==0"
      style="width:100%;height:100%;display:flex;align-items:center;justify-content: center;"
    >
      <el-empty description="暂无订单数据"></el-empty>
      <!-- <img :src="require('../assets/empty.jpg')" alt style="width:30%;height:30%;" /> -->
    </div>
    <el-pagination
      v-if="total>0 && total/10>1"
      background
      layout="prev, pager, next"
      @current-change="handleCurrentChange"
      :total="total"
    ></el-pagination>
    <el-dialog title="请扫码付款" :destroy-on-close="true" :visible.sync="dialogVisible" width="300px">
      <div>
        <div class="payWay">
          <el-radio-group v-model="payWay" size="mini">
            <el-radio label="weixin" border>微信</el-radio>
            <el-radio label="alipay" border>支付宝</el-radio>
          </el-radio-group>
        </div>
        <vue-qr :text="payUrl" :size="240"></vue-qr>
      </div>
    </el-dialog>
    <el-dialog
      id="eldefault"
      title="请填写申诉原因"
      :destroy-on-close="true"
      :visible.sync="dialogVisiblereturn"
    >
      <el-form ref="form" :model="from">
        <el-form-item
          prop="refundReason"
          :rules="{ required: true, message: '申诉原因', trigger: 'blur' }"
          label="申诉原因"
        >
          <el-input
            style="width:100%"
            type="textarea"
            v-model="from.refundReason"
            autocomplete="off"
            placeholder="申诉原因"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisiblereturn = false">取 消</el-button>
        <el-button type="primary" @click="dialogForm" :loading="returnLoading">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog width="70%" :visible.sync="phonePayay" title="支付方式">
      <el-radio-group v-model="payWayByphone" size="mini">
        <el-radio label="weixin" border>微信</el-radio>
        <el-radio label="alipay" border>支付宝</el-radio>
      </el-radio-group>
      <el-button
        style="margin-top:20px"
        type="danger"
        :loading="isLoadingPAY && item.id == itemid"
        @click="payPhoneButton"
      >立即付款</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { orderList } from "../api/api";
import {
  addressList,
  unifiedorder,
  statusPay,
  returnMoney,
  prepay,
  aliunifiedorder,
  createOrderAlipay
} from "@/api/api.js";
import vueQr from "vue-qr";
import ap from "./ap";
export default {
  name: "orderList",
  data() {
    return {
      total: null,
      orderList: [],
      params: {
        pageNo: 0,
        pageSize: 10,
        pageType: "P",
        uid: this.$store.getters["userId"]
      },
      itemid: null,
      isLoading: false,
      payUrl: null,
      dialogVisible: false,
      inter: null,
      from: {
        refundReason: ""
      },
      dialogVisiblereturn: false,
      payPrice: null,
      returnLoading: false,
      payWay: "weixin",
      isLoadingPAY: false,
      phonePayay: false,
      payWayByphone: "weixin"
    };
  },
  watch: {
    payWay() {
      this.pay();
    }
  },
  created() {
    this.getOrderList();
    this.$bus.$on("orderChange", () => {
      this.getOrderList();
    });
  },
  beforeDestroy() {
    this.$bus.$off("orderChange");
  },
  props: {
    paidParams: {
      type: Number,
      default: 3
    },
    status: [String, Number]
  },
  components: {
    vueQr
  },
  beforeDestroy() {
    clearInterval(this.inter);
    this.$bus.$off("orderChange");
  },
  methods: {
    dialogForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          this.returnLoading = true;
          const { data } = await returnMoney({
            id: this.itemid,
            refundPrice: this.payPrice,
            refundReason: this.from.refundReason
          });
          this.$notify({
            title: "申诉申请成功",
            type: "success"
          });
          setTimeout(() => {
            this.returnLoading = false;
            this.dialogVisiblereturn = false;
          }, 500);

          this.getOrderList();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
      this.$bus.$emit("orderChange");
    },
    getStatus(status, paid) {
      console.log("statusss", status);
      if (status == -1) {
        return "申诉中";
      }
      if (status == -3) {
        return "申诉成功";
      }
      if (status == 0 && paid == 0) {
        return "待支付";
      }
      if (status == 0 && paid == 1) {
        return "待发货";
      }
      if (status == 1 && paid == 1) {
        return "已发货";
      }
    },
    toItem(item) {
      console.log("item", item);
      this.$router.push({
        path: "/productDetail",
        query: { userId: item.productList[0].id }
      });
    },
    async rebturnMoney(item) {
      console.log("uten", item);
      this.itemid = item.id;
      this.payPrice = item.payPrice;
      this.dialogVisiblereturn = true;
    },
    async getOrderList() {
      const { data } = await orderList({
        pageNo: this.params.pageNo,
        pageSize: this.params.pageSize,
        pageType: "P",
        uid: this.$store.getters["userId"],
        paid: this.paidParams === 3 ? null : this.paidParams,
        status: this.status
      });
      this.total = data.count;
      this.orderList = data.data;
    },
    handleCurrentChange(val) {
      this.params.pageNo = val - 1;
      this.getOrderList();
    },
    async pay(item) {
      clearInterval(this.inter);
      this.isLoading = true;
      if (item) {
        this.itemid = item.id;
      }
      if (this.payWay == "weixin") {
        const urlPay = await unifiedorder({
          id: this.itemid
        });
        this.payUrl = urlPay.data.code_url;
      }
      if (this.payWay == "alipay") {
        const urlPay = await aliunifiedorder({
          id: this.itemid
        });
        this.payUrl = urlPay.data.code_url;
      }
      // const urlPay = await unifiedorder({
      //   id: item.id
      // });
      // this.payUrl = urlPay.data.code_url;
      setTimeout(() => {
        this.isLoading = false;
      }, 500);
      this.dialogVisible = true;
      this.inter = setInterval(() => {
        statusPay({
          id: this.itemid
        }).then(res => {
          if (res.data.paid == 1) {
            clearInterval(this.inter);
            this.dialogVisible = false;
            this.$notify({
              title: "支付成功！",
              type: "success"
            });
            this.getOrderList();
            this.$bus.$emit("orderChange");
          }
        });
      }, 3000);
      setTimeout(() => {
        clearInterval(this.inter);
      }, 900000);
    },
    alipay_H5(data) {
      const div = document.createElement("div");
      div.innerHTML = data;
      document.body.appendChild(div);
      //document.forms.alipaysubmit.submit();

      var queryParam = "";

      Array.prototype.slice
        .call(document.querySelectorAll("input[type=hidden]"))
        .forEach(function(ele) {
          queryParam += "&" + ele.name + "=" + encodeURIComponent(ele.value);
        });
      var gotoUrl = document.forms.punchout_form.action + queryParam;
      _AP.pay(gotoUrl);
    },
    async payDer(item) {
      this.isLoading = true;
      this.itemid = item.id;
      const urlPay = await unifiedorder({
        id: item.id
      });
      this.payUrl = urlPay.data.code_url;
      setTimeout(() => {
        this.isLoading = false;
      }, 500);
      // console.log(this.payUrl);
      // document.getElementById("spanId").click();
      // window.open("weixin://wxpay/bizpayurl?pr=J40W1Ibzz", "_self");
      // window.location.reload('weixin://wxpay/bizpayurl?pr=J40W1Ibzz');
      // window.location.href = 'weixin://wxpay/bizpayurl?pr=J40W1Ibzz'+'&random='+Math.random();
      window.location.href = this.payUrl;
    },
    async payPhoneButton() {
      this.isLoadingPAY = true;
      if (this.payWayByphone == "weixin") {
        const res = await prepay({
          id: this.itemid,
          openId: window.sessionStorage.getItem("openId")
        });
        WeixinJSBridge.invoke(
          "getBrandWCPayRequest",
          {
            appId: res.data.appId, //公众号ID，由商户传入
            timeStamp: res.data.timeStamp, //时间戳，自1970年以来的秒数
            nonceStr: res.data.nonceStr, //随机串
            package: res.data.prepayId,
            signType: res.data.signType, //微信签名方式：
            paySign: res.data.paySign //微信签名
          },
          res => {
            this.phonePayay = false
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              this.$notify({
                title: "支付成功！",
                type: "success"
              });
              this.getOrderList();
              this.$bus.$emit("orderChange");
            }
            if (res.err_msg == "get_brand_wcpay_request:fail") {
              this.$notify({
                title: "支付失败！",
                type: "success"
              });
              this.getOrderList();
              this.$bus.$emit("orderChange");
            }
          }
        );
        this.isLoadingPAY = false;
      } else {
        const alires = await createOrderAlipay({
          id: this.itemid
        });
        this.alipay_H5(alires.data.form);
        this.isLoadingPAY = false;

        this.inter = setInterval(() => {
          statusPay({
            id: this.itemid
          }).then(res => {
            this.phonePayay = false
            if (res.data.paid == 1) {
              clearInterval(this.inter);
              this.dialogVisible = false;
              this.$notify({
                title: "支付成功！",
                type: "success"
              });
              this.getOrderList();
              this.$bus.$emit("orderChange");
            }
          });
        }, 3000);
        setTimeout(() => {
          clearInterval(this.inter);
        }, 900000);
      }
    },
    async payPhone(item) {
      this.phonePayay = true;
      this.itemid = item.id;
    }
  }
};
</script>

<style lang="scss">
#eldefault {
  .el-dialog {
    width: 90% !important;
  }
}
.el-tabs__active-bar {
  background-color: transparent;
}
.el-tabs__header {
  padding: 10px;
}
.el-tabs__nav {
  width: 100%;
}
.el-tabs__nav-wrap.is-scrollable {
  padding: none;
}
.el-tabs__nav-next {
  display: none;
}
.el-tabs__nav-prev {
  display: none;
}

.el-tabs__nav-scroll {
  display: flex;
  justify-content: center;
  overflow: auto;
}
.order {
  border: 1px solid #e4eaec;
  margin-bottom: 20px;
  border-top: none;
  .order_status {
    padding: 20px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    .order_status_title {
      color: #f96868 !important;
      font-size: 1.286rem;
      text-align: left;
      margin-bottom: 10px;
      text-align: left;
    }
  }
  .order_items {
    border-top: 1px solid #e4eaec;
    .order_item_detail {
      display: flex;
      align-items: center;
    }
  }
}
</style>